/**
 * @file 播放页
 * @module pages/play
 * @author 月落 <yueluo.yang@qq.com>
 */

/**
 * @requires config/navbar - 导航配置
 * @requires config/topic - 主题配置
 * @requires models/music - 音乐功能
 * @requires models/story - 故事功能
 * @requires libs/router - 路由跳转
 */
import { play_navbars } from '../../config/navbar';
import { TOPIC } from '../../config/topic';
import musicModel from '../../models/music';
import storyModel from '../../models/story';
import router from '../../libs/router';
import tools from '../../libs/tools';

// 获取数据仓库
const { $store } = getApp();

Page({
  /**
   * @property {string} topic - 当前主题
   * @property {object} playParams - 播放所需参数
   * @property {object} navbars - 图标导航配置
   * @property {boolean} isPlaying - 正在播放
   * @property {object} audioManager - 音频管理器
   * @property {number} audioProgress - 音频播放进度
   * @property {number} audioDuration - 音频总时长
   */
  data: {
    topic: '',
    playParams: '',
    navbars: play_navbars,
    isPlaying: false,
    audioManager: null,
    audioProgress: 0,
    audioDuration: 0
  },

  onLoad () {
    const { topic, playParams } = $store.state;

    this.setData({
      topic,
      playParams
    });

    // 初始化
    this.init();
  },

  /**
   * @description 初始化函数
   * @returns {void}
   */
  init () { 
    // 初始化音频播放器
    this.initPlayAudio();
  },

  /**
   * @description 初始化音频播放器
   * @returns {void}
   */
  initPlayAudio () {
    if (this.data.audioManager) return this.data.audioManager.play();
    
    const audioManager = wx.getBackgroundAudioManager();

    // 初始化音频事件监听
    this.initAudioListeners(audioManager);

    const { topic } = this.data;

    switch (topic) {
      case TOPIC.MUSIC:
        // 播放音乐
        this.initMusicAudio(audioManager);
        break;
      case TOPIC.STORY:
        // 播放故事
        this.initStoryAudio(audioManager);
        break;
      default:
        break;
    }
  },

  /**
   * @description 播放音乐
   * @param {object} audioManager - 音频播放器
   * @returns {void} 
   */
  async initMusicAudio (audioManager) {
    const { id, title, author, imgUrl } = this.data.playParams;
    const { result } = await musicModel.getMusicUrl(id),
          { code, message, data: { url } } = result; 

    if (code === 0 && url) {
     return this.playAudio({
      audioManager,
      title,
      author,
      imgUrl,
      url
     });
    } 

    console.log(code, message, url);
    router.goBack();
  },

  /**
   * @description 播放音乐
   * @param {object} audioManager - 音频播放器
   * @returns {void} 
   */
  async initStoryAudio (audioManager) {
    const { id, title, imgUrl } = this.data.playParams;
    const { result } = await storyModel.getAudioUrl(id),
          { code, message, data: { url } } = result; 
    
    if (code === 0 && url) {
      return this.playAudio({
        audioManager,
        title,
        author: '月落',
        imgUrl,
        url
      });
      } 

    console.log(code, message, url);
    router.goBack();
  },

    /**
   * @description 播放音频
   * @param {object} audioManager - 音频播放器
   * @param {string} title - 名称
   * @param {string} author - 作者
   * @param {string} imgUrl - 图片地址 
   * @param {string} url - 播放地址
   * @returns {void}
   */
  playAudio ({ audioManager, title, author, imgUrl, url }) {
    console.log(title, author, imgUrl, url);

    audioManager.title = title;
    audioManager.epname = title;
    audioManager.singer = author;
    audioManager.coverImgUrl = imgUrl;
    audioManager.src = url;

    // 循环换取音频总长度（获取音频有延迟）
    let getDurationTimer = setInterval(() => {
      const totalTime = audioManager.duration;

      if (typeof totalTime === 'number' && totalTime) {
        clearInterval(getDurationTimer);
        this.setData({
          audioDuration: Math.round(totalTime)
        });
      }
    }, 300)

    this.setData({
      audioManager
    }, () => tools.showLoading());
  },

  /**
   * @description 初始化音频监听事件
   * @param {object} audioManager - 音频管理器
   * @returns {void} 
   */
  initAudioListeners (audioManager) {
    audioManager.onPlay(() => {
      console.log('[audio]：', 'onPlay');
      this.setData({
        isPlaying: true
      }, () => tools.hideLoading());
    });

    ['onPause', 'onStop', 'onError', 'onEnded'].forEach(method => {
      audioManager && audioManager[method](() => {
        console.log('[audio]：', method);

        this.setData({
          isPlaying: false
        });

        if (method === 'onEnded') {
          this.setData({
            audioProgress: 0,
            audioManager: null
          });
        }
      })
    });

    audioManager.onTimeUpdate(() => {
      const { audioManager, audioDuration } = this.data;

      if (audioManager && audioDuration) {
        this.setData({
          audioProgress: Math.round(audioManager.currentTime)
        });
      }
    });
  },

  /**
   * @description 导航栏点击事件处理
   * @param {object} e - 事件源
   * @returns {void} 
   */
  onIconBtnClick (e) {
    const { action } = e.currentTarget.dataset;

    switch (action) {
      case 'back':
        router.goBack();
        break;
      case 'collect':
        break;
      default:
        console.log('no matching entries.');
        break;
    }
  },

  /**
   * @description 播放、暂停音频
   * @returns {void}
   */
  onAudioClick () { 
    const { isPlaying, audioManager } = this.data;
    audioManager && audioManager[isPlaying ? 'pause' : 'play']();
  }
})